package swu.cx.learning_10_17

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup

class MyGroup:ViewGroup {
    val space = 20
    constructor(context: Context, attrs: AttributeSet):super(context,attrs){

    }
        //测量自己的尺寸
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
            val parentWidth = MeasureSpec.getSize(widthMeasureSpec)
            val parentHeight = MeasureSpec.getSize(heightMeasureSpec)
            var childWidth =if(childCount==1) parentWidth-2*space else (parentWidth-3*space)/2
            val count = childCount/2+childCount%2
            var childHeight = (parentHeight-(count+1)*space)/count

         for (i in 0 until childCount){
             val child = getChildAt(i)
             val widthSpec = MeasureSpec.makeMeasureSpec(childWidth,MeasureSpec.EXACTLY)
             val heightSpec = MeasureSpec.makeMeasureSpec(childHeight,MeasureSpec.EXACTLY)
             child.measure(widthSpec,heightSpec)
         }
    }
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
            var left = space
            var top = space
            for (i in 0 until childCount){
                val child = getChildAt(i)
                child.layout(left,top,left+child.measuredWidth,top+child.measuredHeight)
               left = if(i%2==0)  space+child.measuredWidth else space
                if (i%2!=0){
                    top+=(child.measuredHeight+space)
                }else{
                    left+=space
                }
            }
    }
}